package com.tulele.vtool.task.async;

import com.alibaba.fastjson.JSONObject;
import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.mapper.log.PushHeadLogMapper;
import com.tulele.vtool.bus.model.ArticleInfo;
import com.tulele.vtool.bus.model.UserBrandInfo;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.model.log.PushHeadLog;
import com.tulele.vtool.bus.model.thirdparty.WxNotifyMsgSetInfo;
import com.tulele.vtool.bus.model.thirdparty.WxPushUserInfo;
import com.tulele.vtool.bus.service.*;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserGroupOpenId;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SpringContextUtil;
import com.tulele.vtool.util.SysConstant;
import com.tulele.vtool.util.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Component
@Slf4j
public class SixthTimeArticleMsgAsyncTask {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserService userService;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    @Autowired
    private PushHeadLogMapper pushHeadLogMapper;

    @Autowired
    private IUserBrandService userBrandService;

    @Value("${NotInvolvedInActivities}")
    private String notInvolvedInActivities;//不参与活动的 公众号

    @Value("${RecommendedCourses}")
    private String recommendedCourses;//推课程的 公众号

    @Autowired
    private UserGroupGzhService userGroupGzhService;


    //年末
    @Async("taskExecutor")
    public Integer execute20210208(String redisKey, UserInfo userInfo, Integer headId, String profile) throws WxErrorException {

        Integer ret = 2;
        String detailLog = "";
        try {
            WxPushUserInfo wxPushUserInfo = new WxPushUserInfo();
            wxPushUserInfo.setOpenId(userInfo.getOpenId());

            UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
            if (ugoId != null) {
                wxPushUserInfo.setOpenId(ugoId.getOpenId());
            }

            wxPushUserInfo.setUserId(userInfo.getUserId());

            if (wxPushUserInfo != null) {
                PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
                //20200530 循环推送
                Integer number = 1;
                Object pushNumberObj = redisCacheUtil.getCacheObject("push2010Number" + wxPushUserInfo.getUserId());
                if (pushNumberObj != null) {
                    number = (Integer) pushNumberObj;
                    if (number > 2) {
                        number = 1;
                    }
                }
                redisCacheUtil.setCacheObject("push2010Number" + wxPushUserInfo.getUserId(), number + 1, 100000);
                //20200530 循环推送

                String kefuMsg = "";

                String notVipMsg = "@" + userInfo.getNickName() + "，您已获得高级推广权限~\n\n" +
                        "\uD83D\uDE18 只要您发了文章~有人通过你的文章关注开通会员，您会收到一笔奖励金~\n\n" +
                        "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=获取爆文&msgmenuid=+++\">赶紧发文推广拿奖金吧>></a>\n\n" +
                        "\uD83D\uDCB0 <a href=\"weixin://bizmsgmenu?msgmenucontent=邀请有奖&msgmenuid=+++\">点击查看我的奖励金>></a>";

                String notVipMsg2  = "\uD83C\uDF80 晚上好，试试打造自己的快速获客通道吧！\n\n" +
                        "=====常见功能使用=====\n\n" +
                        "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=获取爆文&msgmenuid=+++\">点击领取【最新爆文】</a>\n\n" +
                        /*"\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=人脉广场&msgmenuid=+++\">加粉丝到【人脉广场】</a>\n\n" +*/
                        "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=客户&msgmenuid=+++\">点击回访【今日客户】</a>\n\n" +
                        "⭕ <a href=\"weixin://bizmsgmenu?msgmenucontent=邀请有奖&msgmenuid=+++\">分享文章能获得邀请奖金？点这里去邀请别人 >></a>\n\n" +
                        "----------------------\n\n" +
                        "↙ <a href=\"weixin://bizmsgmenu?msgmenucontent=订阅明天文章&msgmenuid=+++\">左下方回复数字【 5 】订阅明天早晚打卡！</a>";

                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
                if (weixinService == null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile, weixinService);
                }

                WxMpKefuMessage.WxArticle wxArticle = null;
                //kefuMsg = articleService.generateUserPushArticleInfoThird(wxPushUserInfo.getUserId(), profile);
                if (number.equals(1)) {

                    if (!userInfo.getVipStatus().equals(1)) {
                        String articleTypeName = "";// 默认值
                        String articleTypeIds = articleService.getUserArticleType(userInfo.getUserId());// 获取用户关注的类型
                        if (StringUtils.isNotBlank(articleTypeIds)) {
                            String userFirstArticleType = articleTypeIds.split(",")[0];
                            articleTypeName = articleService.getArticleTypeNameById(Integer.valueOf(userFirstArticleType));// 第一个类型的名称
                        }

                        wxArticle = new WxMpKefuMessage.WxArticle();
                        wxArticle.setTitle("[" + articleTypeName + "]专属优惠券");//平时
                        wxArticle.setDescription("马上领取！");
                        wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo.jpg"+"?"+SysConstant.OSS_PAR_80_80);
                        String accessUrl = sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";
                        wxArticle.setUrl(accessUrl);
                    } else {
                        kefuMsg = notVipMsg;
                    }
                } else {
                    if (!userInfo.getVipStatus().equals(1)) {
                        kefuMsg  = "晚上好，精准获客的步骤坚持不能少！\n\n" +
                                "=====获客流程=====\n\n" +
                                "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=获取爆文&msgmenuid=+++\">点我马上获取一批爆文</a>\n\n" +
                                "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=意向客户&msgmenuid=+++\">点击追踪意向客户</a>\n\n" +
                                "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=我的表单&msgmenuid=+++\">点击意向客户表单收集</a>\n\n" +
                                "----------\n\n" +
                                "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=设置我的行业&msgmenuid=+++\">重新设置我的[ 行业 ]</a>\n\n" +
                                "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=订阅明天文章&msgmenuid=+++\">左下方回复数字[ 5 ]订阅明天最新内容</a>";
                    } else {
                        kefuMsg = notVipMsg2;
                    }

                }

                WxMpKefuMessage message = null;
                if (!kefuMsg.equals("")) {
                    if (userInfo.getPhoneModel().equals(SysConstant.IOS)) {
                        kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                    }
                    message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
                } else {
                    message = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(wxPushUserInfo.getOpenId()).build();
                }

                Boolean sendRet = weixinService.getKefuService().sendKefuMessage(message);
                if (sendRet) {
                    ret = 0;
                    detailLog = "成功";
                } else {
                    ret = 1;
                    detailLog = "失败";
                }
            }
        } catch (Exception e) {
            ret = 2;
            detailLog = e.getMessage();
        }

        PushDetailLog pushDetailLog = new PushDetailLog();
        pushDetailLog.setGzhCode(profile);
        pushDetailLog.setUserId(userInfo.getUserId());
        pushDetailLog.setMsgType(8);  //晚上8点
        pushDetailLog.setPushTime(new Date());
        pushDetailLog.setHeadId(headId);
        pushDetailLog.setResult(ret);
        pushDetailLog.setMsg(detailLog);
        pushDetailLogMapper.addPushDetailLog(pushDetailLog);

        return ret;

    }


    //双12修复前备份
    @Async("taskExecutor")
    public Integer execute20211130(String redisKey, UserInfo userInfo, Integer headId, String profile) throws WxErrorException {

        Integer ret = 2;
        String detailLog = "";
        try {
            WxPushUserInfo wxPushUserInfo  = new WxPushUserInfo();
            wxPushUserInfo.setOpenId(userInfo.getOpenId());

            UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
            if (ugoId != null) {
                wxPushUserInfo.setOpenId(ugoId.getOpenId());
            }

            wxPushUserInfo.setUserId(userInfo.getUserId());

            if (wxPushUserInfo != null) {
                PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
                //20200530 循环推送
                Integer number = 1;
                Object pushNumberObj = redisCacheUtil.getCacheObject("push2010Number" + wxPushUserInfo.getUserId());
                if (pushNumberObj != null) {
                    number = (Integer) pushNumberObj;
                    if (number > 2) {
                        number = 1;
                    }
                }
                redisCacheUtil.setCacheObject("push2010Number" + wxPushUserInfo.getUserId(), number + 1, 100000);
                //20200530 循环推送

                String kefuMsg = "";

                String notVipMsg = "@"+userInfo.getNickName()+"，您已获得高级推广权限~\n\n" +
                        "\uD83D\uDE18 只要您发了文章~有人通过你的文章关注开通会员，您会收到一笔奖励金~\n\n" +
                        "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=获取爆文&msgmenuid=+++\">赶紧发文推广拿奖金吧>></a>\n\n"+
                        "\uD83D\uDCB0 <a href=\"weixin://bizmsgmenu?msgmenucontent=邀请有奖&msgmenuid=+++\">点击查看我的奖励金>></a>" ;

                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
                if (weixinService == null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile, weixinService);
                }

                WxMpKefuMessage.WxArticle wxArticle = null;
                //kefuMsg = articleService.generateUserPushArticleInfoThird(wxPushUserInfo.getUserId(), profile);
                if (number.equals(1)) {

                    if(!userInfo.getVipStatus().equals(1)) {
                        wxArticle = new WxMpKefuMessage.WxArticle();
                        wxArticle.setTitle("[今日限量发放]30元会员抵扣券");//平时
                        wxArticle.setDescription("请立即前往领取哦>>>");
                        wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo.jpg"+"?"+SysConstant.OSS_PAR_80_80);
                        String accessUrl = sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";
                        wxArticle.setUrl(accessUrl);
                    }else{
                        kefuMsg=notVipMsg;
                    }

                } else if (number.equals(2)) {

                    kefuMsg = "\uD83C\uDF80 晚上好，试试打造自己的快速获客通道吧！\n\n" +
                            "=====常见功能使用=====\n\n" +
                            "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=获取爆文&msgmenuid=+++\">点击领取【最新爆文】</a>\n\n" +
                            /*"\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=人脉广场&msgmenuid=+++\">加粉丝到【人脉广场】</a>\n\n" +*/
                            "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=客户&msgmenuid=+++\">点击回访【今日客户】</a>\n\n" +
                            "⭕ <a href=\"weixin://bizmsgmenu?msgmenucontent=邀请有奖&msgmenuid=+++\">分享文章能获得邀请奖金？点这里去邀请别人 >></a>\n\n" +
                            "----------------------\n\n" +
                            "↙ <a href=\"weixin://bizmsgmenu?msgmenucontent=订阅明天文章&msgmenuid=+++\">左下方回复数字【 5 】订阅明天早晚打卡！</a>";
                }

                WxMpKefuMessage message = null;
                if (!kefuMsg.equals("")) {
                    if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                        kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                    }
                    message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
                } else {
                    message = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(wxPushUserInfo.getOpenId()).build();
                }

                Boolean sendRet = weixinService.getKefuService().sendKefuMessage(message);
                if (sendRet) {
                    ret = 0;
                    detailLog = "成功";
                } else {
                    ret = 1;
                    detailLog = "失败";
                }
            }
        } catch (Exception e) {
            ret = 2;
            detailLog = e.getMessage();
        }

        PushDetailLog pushDetailLog = new PushDetailLog();
        pushDetailLog.setGzhCode(profile);
        pushDetailLog.setUserId(userInfo.getUserId());
        pushDetailLog.setMsgType(8);  //晚上8点
        pushDetailLog.setPushTime(new Date());
        pushDetailLog.setHeadId(headId);
        pushDetailLog.setResult(ret);
        pushDetailLog.setMsg(detailLog);
        pushDetailLogMapper.addPushDetailLog(pushDetailLog);

        return ret;

    }

    //专业号
    @Async("taskExecutor")
    public Integer executeProfessional(String redisKey, UserInfo userInfo, Integer headId, String profile) throws WxErrorException {

        Integer ret = 2;
        String detailLog = "";
        try {

            WxPushUserInfo wxPushUserInfo  = new WxPushUserInfo();
            wxPushUserInfo.setOpenId(userInfo.getOpenId());

            UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
            if (ugoId != null) {
                wxPushUserInfo.setOpenId(ugoId.getOpenId());
            }

            wxPushUserInfo.setUserId(userInfo.getUserId());

            if (wxPushUserInfo != null) {
                PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
                //20200530 循环推送
                Integer number = 1;
                Object pushNumberObj = redisCacheUtil.getCacheObject("push2010Number" + wxPushUserInfo.getUserId());
                if (pushNumberObj != null) {
                    number = (Integer) pushNumberObj;
                    if (number > 2) {
                        number = 1;
                    }
                }
                redisCacheUtil.setCacheObject("push2010Number" + wxPushUserInfo.getUserId(), number + 1, 100000);
                //20200530 循环推送

                String kefuMsg = "";

                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
                if (weixinService == null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile, weixinService);
                }

                WxMpKefuMessage.WxArticle wxArticle = null;
                //if (number.equals(1)) {

                UserBrandInfo userBrandInfo = userBrandService.getUserSelectedBrandInfo(wxPushUserInfo.getUserId());//获取用户的 微站
                List<ArticleInfo> articleInfos = null;
                if (userBrandInfo != null) {//有关注品牌的，推品牌文章
                    articleInfos = articleService.getArticleInfoByBrandForCreateTime(userBrandInfo.getBrandId(), 1);
                } else {//没有关注品牌的，推正能量文章
                    articleInfos = articleService.getArticleInfoByTypeForCreateTime(1, 1);//正能量
                }
                if (articleInfos != null && articleInfos.size() > 0) {
                    wxArticle = new WxMpKefuMessage.WxArticle();
                    wxArticle.setTitle(articleInfos.get(0).getArticleTitle());
                    //wxArticle.setDescription(articleInfos.get(0).getArticleDesc());
                    wxArticle.setDescription("回复【9】获取更多爆文");

                    WxMpKefuMessage tiWKM = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(articleInfos.get(0).getArticleDesc()).build();//先发配文
                    weixinService.getKefuService().sendKefuMessage(tiWKM);

                    wxArticle.setPicUrl(articleInfos.get(0).getArticleImgUrl()+"?"+SysConstant.OSS_PAR_80_80);
                    wxArticle.setUrl(sysGzh.getFrontDomain() + "pages/article/detail.html?t=2&userId=" + wxPushUserInfo.getUserId() + "&articleId=" + articleInfos.get(0).getId());
                }

//            } else if (number.equals(2)) {
//
//                kefuMsg = "欢迎来到提升课堂：\n\n"+
//                        "\uD83C\uDF40<a href=\"weixin://bizmsgmenu?msgmenucontent=XSJQ&msgmenuid=+++\">点击【销售技巧】>></a>\n\n" +
//                        "⭕学习更多沟通话术，和客户讲产品的方法~\n\n" +
//                        "\uD83D\uDC6B<a href=\"weixin://bizmsgmenu?msgmenucontent=JTJY&msgmenuid=+++\">点击【家庭教育】>></a>\n\n" +
//                        "⭕学习科学教育理念和方法，家长都看看~\n\n"+
//                        "\uD83D\uDC49想订阅更多行业信息？点击<a href=\"" + sysGzh.getFrontDomain() + "/pages/article/editBrands.html?v=74\">>>订阅品牌</a>设定想要的内容哦~";
//
//            }

                WxMpKefuMessage message = null;
                if (!kefuMsg.equals("")) {
                    if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                        kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                    }
                    message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
                } else {
                    message = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(wxPushUserInfo.getOpenId()).build();
                }

                Boolean sendRet = weixinService.getKefuService().sendKefuMessage(message);
                if (sendRet) {
                    ret = 0;
                    detailLog = "成功";
                } else {
                    ret = 1;
                    detailLog = "失败";
                }
            }
        } catch (Exception e) {
            ret = 2;
            detailLog = e.getMessage();
        }

        PushDetailLog pushDetailLog = new PushDetailLog();
        pushDetailLog.setGzhCode(profile);
        pushDetailLog.setUserId(userInfo.getUserId());
        pushDetailLog.setMsgType(8);  //晚上8点
        pushDetailLog.setPushTime(new Date());
        pushDetailLog.setHeadId(headId);
        pushDetailLog.setResult(ret);
        pushDetailLog.setMsg(detailLog);
        pushDetailLogMapper.addPushDetailLog(pushDetailLog);

        return ret;
    }



}
